package com.atguigu.yygh.cmn.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;

/**
 * @author mgx
 * @version 1.0
 * @description: TODO
 * @date 2022/8/24 16:17
 */
public class DictListener extends AnalysisEventListener<DictEeVo> {
    // 因为不能交给spring容器管理，所以使用构造函数传入参数
    private DictMapper dictMapper;

    public DictListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) {
        // 逐条操作，通过判断id是否存在来决定是修改还是插入
        // 转化DictEeVo
        Dict dict = new Dict();
        BeanUtils.copyProperties(dictEeVo, dict);
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("id", dictEeVo.getId());
        Integer count = dictMapper.selectCount(dictQueryWrapper);
        if(count > 0) {
            // 说明是修改
            dictMapper.updateById(dict);
        }else {
            dictMapper.insert(dict);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
